<template>
  <view class="order-detail-page">
    <!-- 状态栏 -->
    <view class="status-bar" :class="['status-' + orderInfo.status]">
      <text class="status-text">{{getStatusText(orderInfo.status)}}</text>
      <text class="status-desc">{{statusDesc}}</text>
    </view>
    
    <view class="detail-container">
      <!-- 订单基本信息 -->
      <view class="info-card">
        <view class="info-title">订单信息</view>
        
        <view class="info-item">
          <text class="item-label">订单编号：</text>
          <text class="item-value">{{orderInfo.pao_order}}</text>
        </view>
        
        <view class="info-item">
          <text class="item-label">创建时间：</text>
          <text class="item-value">{{formatTime(orderInfo.create_time)}}</text>
        </view>
        
        <view class="info-item" v-if="orderInfo.pay_time">
          <text class="item-label">支付时间：</text>
          <text class="item-value">{{formatTime(orderInfo.pay_time)}}</text>
        </view>
        
        <view class="info-item" v-if="orderInfo.tk_time">
          <text class="item-label">取消时间：</text>
          <text class="item-value">{{formatTime(orderInfo.tk_time)}}</text>
        </view>
      </view>
      
      <!-- 任务详情 -->
      <view class="info-card">
        <view class="info-title">任务详情</view>
        
        <view class="info-item">
          <text class="item-label">任务标题：</text>
          <text class="item-value">{{orderInfo.title}}</text>
        </view>
        <view class="info-item">
          <text class="item-label">任务地点：</text>
          <text class="item-value">{{orderInfo.colleges }} - {{orderInfo.address}}</text>
        </view>
        <view class="info-item">
          <text class="item-label">任务报酬：</text>
          <text class="item-value price">¥{{orderInfo.price}}</text>
        </view>
        
        <view class="info-item">
          <text class="item-label">联系方式：</text>
          <text class="item-value">{{orderInfo.contact}}</text>
        </view>
        
        <view class="info-item" v-if="orderInfo.remark">
          <text class="item-label">任务描述：</text>
          <text class="item-value">{{orderInfo.remark}}</text>
        </view>
      </view>
      
      <!-- 任务图片 -->
      <view class="info-card" v-if="orderInfo.image && JSON.parse(orderInfo.image).length">
        <view class="info-title">任务图片</view>
        <view class="image-container">
          <image 
            v-for="(item,index) in JSON.parse(orderInfo.image)" 
            :key="index" 
            :src="item.url"
            mode="aspectFill"
            class="task-image"
            @click="previewImage(index)"
          ></image>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons" v-if="showActions">
        <button 
          v-if="orderInfo.status === 0" 
          class="action-btn cancel-btn"
          @click="showCancelDialog"
          :disabled="processing"
        >
          <text v-if="!processing">取消发布</text>
          <text v-else>处理中...</text>
        </button>
        
        <button 
          v-if="orderInfo.status === 1" 
          class="action-btn complete-btn"
          @click="showCompleteDialog"
          :disabled="processing"
        >
          <text v-if="!processing">确认完成</text>
          <text v-else>处理中...</text>
        </button>
      </view>
    </view>
    
    <!-- 取消确认对话框 -->
    <uni-popup ref="cancelDialog" type="dialog">
      <uni-popup-dialog 
        type="warning"
        title="确认取消"
        content="确定要取消发布此任务吗？取消后将于24小时内退款原路返回"
        @confirm="confirmCancel"
        @close="closeCancelDialog"
      ></uni-popup-dialog>
    </uni-popup>
    
    <!-- 完成确认对话框 -->
    <uni-popup ref="completeDialog" type="dialog">
      <uni-popup-dialog 
        type="info"
        title="确认完成"
        content="确认任务已经完成了吗？"
        @confirm="confirmComplete"
        @close="closeCompleteDialog"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      orderInfo: {},
      processing: false,
      useMockData: true, // 设为 false 时使用真实接口数据
      statusDescMap: {
        0: '等待接单中',
        1: '任务进行中',
        2: '任务已完成',
        3: '任务已取消',
        4: '任务状态异常'
      }
    }
  },
  onLoad(options) {
    this.orderId = options.id;
    this.loadOrderDetail();
  },
  computed: {
    statusDesc() {
      return this.statusDescMap[this.orderInfo.status] || '';
    },
    showActions() {
      return this.orderInfo.status === 0 || this.orderInfo.status === 1;
    }
  },
  methods: {
    // 生成假数据
    generateMockOrder() {
      const status = this.orderId % 4; // 根据ID生成不同状态
      const typeList = ['快递代取', '外卖代买', '文件传递', '超市代购'];
      const typeIndex = this.orderId % 4;
      const isPaid = status !== 0;
      
      return {
        id: this.orderId,
        pao_order: 'PO' + new Date().getTime() + this.orderId,
        user_id: 2000 + (this.orderId % 10),
        create_time: new Date().toISOString(),
        type: typeIndex + 1,
        title: `${typeList[typeIndex]}服务`,
        remark: `这是关于${typeList[typeIndex]}的详细描述，请尽快完成。具体要求请查看任务图片。`,
        price: (Math.random() * 50 + 5).toFixed(2),
        status: status,
        contact: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
        image: JSON.stringify([{url: `/static/mock/type-${typeIndex+1}.jpg`}]),
        pay_time: isPaid ? new Date().toISOString() : null,
        pay_type: isPaid ? (this.orderId % 2 === 0 ? 0 : 3) : null, // 0微信 3余额
        tk_time: status === 3 ? new Date().toISOString() : null
      };
    },
    
    // 加载订单详情
    async loadOrderDetail() {
      uni.showLoading({ title: '加载中...' });
      
      if (this.useMockData) {
        await new Promise(resolve => setTimeout(resolve, 500)); // 模拟网络延迟
        this.orderInfo = this.generateMockOrder();
      } else {
        try {
          const res = await this.$http.get('/pao/detail', { 
            params: { id: this.orderId }
          });
          this.orderInfo = res.data;
        } catch (e) {
          uni.showToast({ title: '加载失败', icon: 'none' });
        }
      }
      
      uni.hideLoading();
    },
    
    // 格式化时间
    formatTime(time) {
      if (!time) return '--';
      return time.replace('T', ' ').substr(0, 16);
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '待接单',
        1: '进行中',
        2: '已完成',
        3: '已取消',
        4: '其他'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 预览图片
    previewImage(index) {
      const images = JSON.parse(this.orderInfo.image).map(item => item.url);
      uni.previewImage({
        current: index,
        urls: images
      });
    },
    
    // 显示取消对话框
    showCancelDialog() {
      this.$refs.cancelDialog.open();
    },
    
    // 确认取消订单
    async confirmCancel() {
      this.processing = true;
      try {
        if (this.useMockData) {
          await new Promise(resolve => setTimeout(resolve, 800)); // 模拟网络延迟
          this.orderInfo.status = 3;
          this.orderInfo.tk_time = new Date().toISOString();
          uni.showToast({ title: '取消成功(模拟)', icon: 'success' });
        } else {
          const res = await this.$http.post('/pao/cancel', {
            id: this.orderId
          });
          
          if (res.code === 200) {
            uni.showToast({ title: '取消成功', icon: 'success' });
            this.loadOrderDetail();
          } else {
            uni.showToast({ title: res.msg || '取消失败', icon: 'none' });
          }
        }
      } catch (e) {
        uni.showToast({ title: '请求失败', icon: 'none' });
      } finally {
        this.processing = false;
        this.closeCancelDialog();
      }
    },
    
    // 关闭取消对话框
    closeCancelDialog() {
      this.$refs.cancelDialog.close();
    },
    
    // 显示完成对话框
    showCompleteDialog() {
      this.$refs.completeDialog.open();
    },
    
    // 确认完成任务
    async confirmComplete() {
      this.processing = true;
      try {
        if (this.useMockData) {
          await new Promise(resolve => setTimeout(resolve, 800)); // 模拟网络延迟
          this.orderInfo.status = 2;
          uni.showToast({ title: '完成确认(模拟)', icon: 'success' });
        } else {
          const res = await this.$http.post('/pao/complete', {
            id: this.orderId
          });
          
          if (res.code === 200) {
            uni.showToast({ title: '操作成功', icon: 'success' });
            this.loadOrderDetail();
          } else {
            uni.showToast({ title: res.msg || '操作失败', icon: 'none' });
          }
        }
      } catch (e) {
        uni.showToast({ title: '请求失败', icon: 'none' });
      } finally {
        this.processing = false;
        this.closeCompleteDialog();
      }
    },
    
    // 关闭完成对话框
    closeCompleteDialog() {
      this.$refs.completeDialog.close();
    }
  }
}
</script>

<style scoped>
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.status-bar {
  padding: 40rpx 30rpx;
  color: #fff;
}

.status-0 {
  background-color: #FF9900;
}

.status-1 {
  background-color: #09bb07;
}

.status-2 {
  background-color: #999;
}

.status-3 {
  background-color: #FF5A5F;
}

.status-4 {
  background-color: #666;
}

.status-text {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.status-desc {
  font-size: 28rpx;
  opacity: 0.9;
}

.detail-container {
  padding: 20rpx;
  margin-top: -20rpx;
  border-radius: 20rpx 20rpx 0 0;
  background-color: #f5f5f5;
  position: relative;
  z-index: 1;
}

.info-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.info-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #333;
  border-left: 6rpx solid #09bb07;
  padding-left: 20rpx;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  font-size: 28rpx;
}

.item-label {
  color: #666;
  width: 160rpx;
}

.item-value {
  color: #333;
  flex: 1;
}

.price {
  color: #FF5A5F;
  font-weight: bold;
}

.image-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.task-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
}

.action-buttons {
  margin-top: 40rpx;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.action-btn {
  height: 80rpx;
  line-height: 80rpx;
  font-size: 32rpx;
  border-radius: 40rpx;
}

.cancel-btn {
  background-color: #fff;
  color: #FF5A5F;
  border: 1rpx solid #FF5A5F;
}

.complete-btn {
  background-color: #09bb07;
  color: #fff;
}

.action-btn[disabled] {
  opacity: 0.6;
}
</style>